import { getToken } from '@/utils'
import { useTitle } from '@vueuse/core'
import type { NavigationGuardNext, RouteLocationNormalized, Router } from 'vue-router'
import { RouteNameMap, whitelistRoutes } from './routes'

/**
 * 路由守卫函数
 * @param router 路由实例
 */
export default function createRouterGuide(router: Router) {
  router.beforeEach((to, from, next) => {
    window.$loadingBar?.start()
    handleRouterAction(to, from, next)
  })
  router.afterEach((to) => {
    // 设置 document 的 title
    useTitle(to.meta.title as string)
    // 结束 loading bar
    window.$loadingBar?.finish()
  })
}

function routeRule(to: RouteLocationNormalized) {
  const hasLogin = getToken() ? true : false
  const inWhiteList = whitelistRoutes.includes(to.name as string)
  const isLogin = to.name === RouteNameMap.get('login')
  const loginRedirectName = to.query.redirectName as string
  const rootName = RouteNameMap.get('root') as string
  // 登录状态下跳转登录页面，重定向
  if (hasLogin && isLogin) return { name: loginRedirectName || rootName }
  // 登录或白名单，直接跳转
  if (hasLogin || inWhiteList) return null
  // 未登录，且不在白名单中，跳转到登录页面，且带上需要跳转的页面
  return { name: RouteNameMap.get('login'), query: { redirectName: to.name as string } }
}

function handleRouterAction(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const target = routeRule(to)
  if (target === null) next()
  else next(target)
}
